package cn.hh.lambda;

import org.junit.Test;

import java.util.Comparator;

/**
 * @Author huangh
 * @date 2021/09/23
 * @Description:
 */
public class Demo4 {
    /**
     * 比较两个数
     * @param str1
     * @param str2
     * @param comparator
     * @return
     */
    public static int compareString(String str1, String str2, Comparator<String> comparator) {
        return comparator.compare(str1, str2);
    }

    @Test
    public void test1(){
        String str1 = "abc";
        String str2 = "abcd";

        int i = compareString(str1, str2, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        });
        System.out.println(i);

    }

    @Test
    public void test2(){
        String str1 = "abc";
        String str2 = "abcd";

        Comparator comparator = new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        };
        int i = compareString(str1, str2, comparator);

        System.out.println(i);
    }

    @Test
    public void test3(){
        String str1 = "abc";
        String str2 = "abcd";

        //这里改为lambda要增加泛型
        Comparator<String> comparator = (String s1, String s2) ->{
            return s1.length() - s2.length();
        };
        int i = compareString(str1, str2, comparator);

        System.out.println(i);
    }

    @Test
    public void test4(){
        String str1 = "abc";
        String str2 = "abcd";

        //这里改为lambda要增加泛型
        Comparator<String> comparator = (String s1, String s2) ->{
            return s1.length() - s2.length();
        };
        int i = compareString(str1, str2, comparator);
        System.out.println(i);

        // 改进一下，跳过赋值这一步，直接把整个Lambda传给compareString()方法：
        int a = compareString(str1, str2,(String s1, String s2) ->{
            return s1.length() - s2.length();
        });
        System.out.println(a);

        //把return省略
        int x = compareString(str1, str2,(String s1, String s2) ->
           s1.length() - s2.length()
        );
        System.out.println(x);

        int y = compareString(str1,str2,Comparator.comparingInt(String::length));
        System.out.println(y);
    }


}
